package com.wu.database.lazy.starter.simple.controller;

//import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.wu.database.lazy.starter.simple.domain.SysUser;
import com.wu.database.lazy.starter.simple.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.wu.framework.core.exception.RuntimeExceptionFactory;
import org.wu.framework.lazy.orm.database.lambda.stream.lambda.LazyLambdaStream;
import org.wu.framework.web.spring.EasyController;

import javax.sql.DataSource;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * describe : 事物使用
 *
 * @author : Jia wei Wu
 * @version 1.0
 * @date : 2022/3/6 12:46
 */
@Tag(name = "事物使用")
@EasyController
public class TransactionalController {
    private final SysUserService sysUserService;
    private final LazyLambdaStream lazyLambdaStream;
    private final DataSource dataSource;

    public TransactionalController(SysUserService sysUserService, LazyLambdaStream lazyLambdaStream, DataSource dataSource) {
        this.sysUserService = sysUserService;
        this.lazyLambdaStream = lazyLambdaStream;
        this.dataSource = dataSource;
    }


//    @DSTransactional
    @Transactional(rollbackFor = Exception.class)
    @Operation(summary ="用户信息 事物使用")
    @PostMapping("/transactional")
    public String upsertTransactional() {
        final SysUser sysUser = new SysUser();
        sysUser.setId(1L);
        sysUser.setCreateTime(new Date());
        sysUser.setUsername(LocalDateTime.now()+"hahah");
        sysUserService.updateById(sysUser);
        sysUser.setCreateTime(new Date());
        sysUser.setUsername("hahahwww");
        lazyLambdaStream.upsert(sysUser);
        return "Sucess";
    }

    @Transactional(rollbackFor = Exception.class)
    @Operation(summary ="用户信息 事物回滚")
    @PostMapping("/rollback")
    public String rollback() {
        final SysUser sysUser = new SysUser();
        sysUser.setId(1L);
        sysUser.setCreateTime(new Date());
        sysUser.setUsername(LocalDateTime.now()+"hahah");
        sysUserService.updateById(sysUser);
        sysUser.setCreateTime(new Date());
        sysUser.setUsername("hahahwww");
        lazyLambdaStream.upsert(sysUser);
        RuntimeExceptionFactory.of("rollback");
        return "Sucess";
    }

}
